<template>
	<section>
		<el-row>
			<el-col :span="24">
				<div class="tableTitle">用户列表</div>
				<el-row style="margin: 10px 0;text-align: right;padding-right: 20px;">
					<el-button type="primary" @click="add" style="">添加</el-button>
				</el-row>

				<el-table :data="tableData" border stripe style="width: 100%">
					<el-table-column prop="userId" label="ID">
					</el-table-column>
					<el-table-column prop="username" label="用户名">
					</el-table-column>
					<el-table-column prop="password" label="密码">
					</el-table-column>
					<el-table-column prop="name" label="真实姓名">
					</el-table-column>
					<el-table-column prop="mobile" label="手机号">
					</el-table-column>
					<el-table-column label="角色" prop="roles">
					</el-table-column>
					<el-table-column label="操作" width="300">
						<template slot-scope="scope">
							<el-button size="small" type="primary" @click="setpsd(scope.row)">重置密码</el-button>
							<el-button size="small" type="warning" @click="modify(scope.row)">编辑</el-button>
							<el-button size="small" type="danger" @click="deleteUser(scope.$index,scope.row)">删除</el-button>
						</template>
					</el-table-column>

				</el-table>
			</el-col>
		</el-row>
		<el-dialog title="添加用户" :visible.sync="dialogFormVisible">
			<el-form :model="dataForm" ref="dataForm" :rules="rules">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="dataForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名" prop="name">
					<el-input v-model="dataForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="dataForm.mobile" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="角色" prop="role">
					<el-checkbox-group v-model="dataForm.roleIds">
						<el-checkbox :label="item.roleId" :key="item.roleId" v-for="item in roleList" name="type">{{item.roleName}}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="userSave('dataForm')">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="重置密码" :visible.sync="passwordFormVisible">
			<el-form :model="passwordForm" ref="passwordForm" :rules="rules2">
				<el-form-item label="新密码" prop="password">
					<el-input v-model="passwordForm.password" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="confirmPassword">
					<el-input v-model="passwordForm.confirmPassword" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="passwordFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="passwordSave('passwordForm')">确 定</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { userSave, userDelete, userList, userUpdate, roleList } from '@/api/getData'
	import { isPhoneVailable } from '@/config/mUtils'
	export default {
		data() {
			var validateMobile = (rule, value, callback) => {
				if(value === '') {
					callback(new Error('请输入手机号'));
				} else {
					if(isPhoneVailable(value)) {
						callback(new Error('请输入正确的手机号'));
					}
					callback();
				}
			};
			var validatePass = (rule, value, callback) => {
				if(value === '') {
					callback(new Error('请再次输入密码'));
				} else if(value !== this.passwordForm.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				dialogFormVisible: false,
				passwordFormVisible: false,
				tableData: [],
				roleList: [],
				dataForm: {
					userId: "",
					name: "",
					username: "",
					mobile: "",
					roleIds: [],
				},
				passwordForm: {
					password: "",
					confirmPassword: ""
				},
				rules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 30,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
					name: [{
							required: true,
							message: '请输入真实姓名',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 30,
							message: '长度在 1 到 30 个字符',
							trigger: 'blur'
						}
					],
					mobile: [{
						validator: validateMobile,
						trigger: 'blur'
					}],
					role: [{
						type: 'array',
						required: true,
						message: '请至少选择一个角色',
						trigger: 'change'
					}],

				},
				rules2: {
					password: [{
							required: true,
							message: '请输入新密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 30,
							message: '长度在 6 到 30 个字符',
							trigger: 'blur'
						}
					],
					confirmPassword: [{
						validator: validatePass,
						trigger: 'blur'
					}],
				},
			};
		},
		created() {
			this.initData();
		},
		methods: {
			async initData() {
				try {
					const returnData = await userList({
						pageSize: "100",
						pageNum: "1",
					});
					if(returnData.code == "0") {
						this.roleListFun(null, returnData.list.rows);
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async roleListFun(row, data) {
				try {
					const returnData = await roleList({
						pageSize: "100",
						pageNum: "1",
					});
					if(returnData.code == "0") {
						this.roleList = returnData.list.rows;
						if(row == null) {
							this.dataForm.userId = "";
							this.dataForm.name = "";
							this.dataForm.username = "";
							this.dataForm.mobile = "";
							this.dataForm.roleIds = [];
						} else {
							console.log(row)
							this.dataForm.userId = row.userId;
							this.dataForm.name = row.name;
							this.dataForm.username = row.username;
							this.dataForm.mobile = row.mobile;
							this.dataForm.roleIds = row.roleIds;
						}
						if(data != undefined) {
							data.forEach(function(item) {
								let roleName = "";
								item.roleIds.forEach(function(obj) {
									returnData.list.rows.forEach(function(role) {
										if(obj == role.roleId) {
											roleName += role.roleName + "  ";
										}
									});
								});
								item.roles = roleName;
							});
							this.tableData = data;
						}

					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async deleteUser(index, row) {
				try {
					let returnData = await userDelete({
						id: row.userId
					});
					if(returnData.code == "0") {
						this.tableData.splice(index, 1);
						this.$message({
							message: "删除成功！",
							type: 'success'
						});
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async userSave(formData) {
				this.$refs[formData].validate(async(valid) => {
					if(valid) {
						try {
							let result = null;
							if(this.dataForm.userId != "") {
								result = await userUpdate(this.dataForm);
							} else {
								result = await userSave(this.dataForm);
							}
							if(result.code == "0") {
								this.$message({
									type: 'success',
									message: '保存成功'
								});
								this.dialogFormVisible = false;
								this.initData();
							}
						} catch(err) {
							this.$message({
								type: 'error',
								message: result.msg
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: '请检查输入是否正确',
							offset: 100
						});
						return false;
					}
				});
			},
			add() {
				this.roleListFun();
				this.dialogFormVisible = true;
			},
			modify(row) {
				this.roleListFun(row);
				this.dialogFormVisible = true;
			},
			setpsd() {
				this.passwordFormVisible = true;
			},
			async passwordSave(formData) {
				this.$refs[formData].validate(async(valid) => {
					if(valid) {
						try {
							let result = await userUpdate(this.passwordForm);
							if(result.code == "0") {
								this.$message({
									type: 'success',
									message: '保存成功'
								});
								this.dialogFormVisible = false;
								this.initData();
							}
						} catch(err) {
							this.$message({
								type: 'error',
								message: result.msg
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: '请检查输入是否正确',
							offset: 100
						});
						return false;
					}
				});
			}
		}
	}
</script>

<style scoped>
	.tableTitle {
		background-color: #20a0ff;
		line-height: 40px;
		color: #ffffff;
		padding-left: 10px;
	}
	
	.demo-form-inline {
		margin-top: 20px;
	}
</style>